package com.example.demo.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.dao.ArticleRepository;
import com.example.demo.dao.UserBrowseRepository;
import com.example.demo.domain.EsArticle;
import com.example.demo.domain.EsUserBrowse;
import com.example.demo.domain.KeywordAndTagMap;
import com.example.demo.req.UserArtIdReq;
import com.example.demo.util.MapValueComparator;
import com.uubee.share.util.UuidUtil;
import com.uubee.share.wrapper.ModelListResult;
import com.zeus.media.dubbo.domain.BrowseHistory;
import com.zeus.media.dubbo.service.history.IBrowseHistoryService;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;

/**
 * 用户浏览记录
 * Created by wengjunjie on 2018/2/7.
 */
@RestController
@RequestMapping("userBrowse")
public class UserBrowseController {
    private static Logger logger = LoggerFactory.getLogger(UserBrowseController.class);
    @Autowired
    private IBrowseHistoryService browseHistoryService;
    @Autowired
    private UserBrowseRepository userBrowseRepository;
    @Autowired
    private ArticleRepository articleRepository;

    @RequestMapping("sync")
    public String syncArticle(BrowseHistory browseHistory) {
        browseHistory.setCorrelationID(UuidUtil.getUuid());
        ModelListResult<BrowseHistory> articleModelListResult = browseHistoryService.pageQueryHistory(browseHistory);
        for (BrowseHistory tmp : articleModelListResult.getModel()) {
            String id = getUserArtId(tmp);
            EsUserBrowse es = userBrowseRepository.findById(id);
            if (es != null) {
                es.setView_count(es.getView_count() + 1);
                es.setLast_update_time(new Date());
                userBrowseRepository.save(es);
                continue;
            }
            logger.info("当前用户浏览的文章id={},es不存在,准备写入es", id);
            EsUserBrowse userBrowse = dataFromBrowseHistory(tmp);
            userBrowseRepository.save(userBrowse);
        }
        return "sync ok";
    }

    private EsUserBrowse dataFromBrowseHistory(BrowseHistory tmp) {
        Date now = new Date();
        EsUserBrowse es = new EsUserBrowse();
        es.setId(getUserArtId(tmp));
        es.setCreate_time(now);
        es.setLast_update_time(now);
        es.setArticle_id(tmp.getArticle_id());
        es.setView_count(1);
        es.setUser_id(tmp.getUser_id());
        return es;
    }

    private String getUserArtId(BrowseHistory tmp) {
        return tmp.getUser_id() + tmp.getArticle_id();
    }

    @RequestMapping("delete")
    public String delete() {
        userBrowseRepository.deleteAll();
        return "delete ok";
    }

    @RequestMapping("arts")
    public List<String> getUserArtIds(UserArtIdReq req) {
        QueryBuilder query = buildQuery(req);
        //step1:当前用户浏览的最喜欢的10篇文章，基于浏览次数+最后阅读时间
        Pageable pageable = new PageRequest(0, 10, Sort.Direction.DESC, "_score");
        Page<EsUserBrowse> esUserBrowses = userBrowseRepository.search(query, pageable);
        List<String> userTopViewArticleIds = idsFromBrowse(esUserBrowses);

        //step2:10篇文章的关键词+类目
        QueryBuilder artIdsQuery = buildQueryForArt(userTopViewArticleIds);
        Iterable<EsArticle> esArticles = articleRepository.search(artIdsQuery);
        KeywordAndTagMap keywordAndTagMap = esArticleToMap(esArticles);

        //step3:基于相近文章的关键词，去搜索es符合的文章列表
        QueryBuilder queryWithKeyAndTag = buildQueryWithKeyAndTag(keywordAndTagMap, req.getArticle_tag());
        Pageable userPageable = new PageRequest(req.getStart(), req.getPageSize(), Sort.Direction.DESC, "_score");
        Iterable<EsArticle> userArticles = articleRepository.search(queryWithKeyAndTag, userPageable);
        return esArticlesToList(userArticles);
    }

    private List<String> esArticlesToList(Iterable<EsArticle> userArticles) {
        List<String> tmp = new ArrayList<>();
        for (EsArticle userArticle : userArticles) {
            tmp.add(userArticle.getId());
        }
        return tmp;
    }

    /**
     * @param map
     * @param article_tag 说明是专题页面的搜索
     * @return
     */
    private QueryBuilder buildQueryWithKeyAndTag(KeywordAndTagMap map, String article_tag) {
        BoolQueryBuilder builder = QueryBuilders.boolQuery()
                .should(QueryBuilders.termsQuery("keywords", map.getKeywordMap().keySet())).minimumNumberShouldMatch(1);
        if (article_tag != null) {
            builder.should(QueryBuilders.termQuery("article_tag", article_tag));
        } else {
            builder.should(QueryBuilders.termsQuery("article_tag", map.getTagMap().keySet()));
        }
        Map<String, Object> params = new HashMap<>();
        params.put("create_time", new Date().getTime());
        FunctionScoreQueryBuilder query2 =
                QueryBuilders.functionScoreQuery(builder).add(ScoreFunctionBuilders.scriptFunction(
                        //如果当前时间=最后更新时间，那么结果等于当前分数
                        new Script("(_score + 1/(create_time-doc['create_time'].value.toDouble()+1))/2"
                                , ScriptService.ScriptType.INLINE, "groovy", params))
                ).scoreMode("first")
                        .boostMode(CombineFunction.REPLACE);

        return query2;
    }

    private KeywordAndTagMap esArticleToMap(Iterable<EsArticle> esArticles) {
        KeywordAndTagMap map = new KeywordAndTagMap();
        Map keywordMap = map.getKeywordMap();
        Map tagMap = map.getTagMap();
        for (EsArticle esArticle : esArticles) {
            for (String keyword : esArticle.getKeywords().split(",")) {
                if (keywordMap.get(keyword) == null) {
                    keywordMap.put(keyword, 1);
                } else {
                    keywordMap.put(keyword, (Integer) keywordMap.get(keyword) + 1);
                }
            }
            if (tagMap.get(esArticle.getArticle_tag()) == null) {
                tagMap.put(esArticle.getArticle_tag(), 1);
            } else {
                tagMap.put(esArticle.getArticle_tag(), (Integer) tagMap.get(esArticle.getArticle_tag()) + 1);
            }
        }
        keywordMap = sortMapByKey(keywordMap);    //按Key进行排序
        tagMap = sortMapByKey(tagMap);    //按Key进行排序
        return map;
    }

    private Map sortMapByKey(Map oriMap) {
        if (oriMap == null || oriMap.isEmpty()) {
            return null;
        }
        Map<String, Integer> sortedMap = new LinkedHashMap<>();
        List<Map.Entry<String, Integer>> entryList = new ArrayList<Map.Entry<String, Integer>>(
                oriMap.entrySet());
        Collections.sort(entryList, new MapValueComparator());

        Iterator<Map.Entry<String, Integer>> iter = entryList.iterator();
        Map.Entry<String, Integer> tmpEntry = null;
        while (iter.hasNext()) {
            tmpEntry = iter.next();
            sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
        }
        return sortedMap;
    }

    private QueryBuilder buildQueryForArt(List<String> userTopViewArticleIds) {
        return QueryBuilders.idsQuery().ids(userTopViewArticleIds);
    }

    private List<String> idsFromBrowse(Page<EsUserBrowse> esUserBrowses) {
        List<String> tmp = new ArrayList<>();
        for (EsUserBrowse esUserBrows : esUserBrowses) {
            tmp.add(esUserBrows.getArticle_id());
        }
        return tmp;
    }

    /**
     * <a href="https://blog.csdn.net/nxgych/article/details/53096255">关于elasticsearch function_score的使用</a>
     *
     * @param req
     * @return
     */
    private QueryBuilder buildQuery(UserArtIdReq req) {
        BoolQueryBuilder query = boolQuery();
        if (req.getUser_id() != null) {
            //query = query.must(QueryBuilders.matchQuery("user_id", req.getUser_id())).boost(4);
            Map<String, Object> params = new HashMap<>();
            params.put("last_update_time", new Date().getTime());
            FunctionScoreQueryBuilder query2 =
                    QueryBuilders.functionScoreQuery(QueryBuilders.boolQuery()
                            .should(QueryBuilders.matchQuery("user_id", req.getUser_id()))
                    ).add(ScoreFunctionBuilders.scriptFunction(
                            //如果当前时间=最后更新时间，那么结果等于当前分数
                            new Script("(_score+doc['view_count'].value.toDouble()/(doc['view_count'].value.toDouble()+10)+1/(last_update_time-doc['last_update_time'].value.toDouble()+1))/2"
                                    , ScriptService.ScriptType.INLINE, "groovy", params))
                    ).scoreMode("first")
                            .boostMode(CombineFunction.REPLACE);
            return query2;
        }
        return query;
    }

}
